import random
import re

from flask import request, session, make_response, jsonify, render_template, redirect, url_for

from app2 import db
from app2.models.models import User
from app2.utils.common.common import vip_get_webservertime, vip_default_time
from app2.utils.sms.ali_sms import send_sms
from . import passport_blue


# @passport_blue.route("/register", methods=["POST"])
# def register():
#     """注册响应"""
#     # print(request.form)
#     # print(request.json)
#     mobile = request.json.get("mobile")  # 提取手机号
#     image_code = request.json.get("image_code")  # 提取用户输入的图片验证码
#     password = request.json.get("password")  # 提取密码
#
#     # session.get("captcha")  # 提取当前页面显示的验证码
#     # print(mobile, image_code, password)
#     if not all([mobile, image_code, password]):
#         ret = {
#             "errno": 1001,
#             "errmsg": "缺少参数"
#         }
#         return jsonify(ret)
#
#     if image_code.lower() != session.get("captcha").lower():
#         ret = {
#             "errno": 1002,
#             "errmsg": "验证码错误"
#         }
#         return jsonify(ret)
#
#     user = User(nick_name=mobile, password_hash=password, mobile=mobile)
#
#     # user = User()
#     # user.nick_name = mobile
#     # user.password_hash = password
#     # user.mobile = mobile
#
#     try:
#         db.session.add(user)
#         db.session.commit()
#         # 存储session
#         session['nick_name'] = mobile
#         session["user_id"] = user.id
#     except Exception as e:
#         db.session.rollback()
#
#     ret = {
#         "errno": 0,
#         "errmsg": "注册成功"
#     }
#
#     return jsonify(ret)
#
#
# @passport_blue.route("/login", methods=["POST"])
# def login():
#     """登录响应"""
#     # print(request.form)
#     # print(request.json)
#     mobile = request.json.get("mobile")  # 提取手机号
#     # image_code = request.json.get("image_code")  # 提取用户输入的图片验证码
#     password = request.json.get("password")  # 提取密码
#
#     # session.get("captcha")  # 提取当前页面显示的验证码
#     # print(mobile, image_code, password)
#     if not all([mobile, password]):
#         ret = {
#             "errno": 2001,
#             "errmsg": "缺少参数"
#         }
#         return jsonify(ret)
#
#     user = User.query.filter(User.mobile == mobile, User.password_hash == password).first()
#
#     if not user:
#         ret = {
#             "errno": 2002,
#             "errmsg": "用户名或密码错误"
#         }
#
#         return jsonify(ret)
#
#     session['nick_name'] = mobile
#     session["user_id"] = user.id
#
#     ret = {
#         "errno": 0,
#         "errmsg": "注册成功"
#     }
#
#     return jsonify(ret)


# @passport_blue.route("/image_code")  # /image_code?code_id=123123123123123
# def image_code():
#     """图片验证码"""
#     from app.utils.captcha.captcha import captcha
#     # # 1. 获取到当前的图片编号id
#     # captcah_id = request.args.get('id')
#     # print(type(captcah_id), captcah_id)
#     # 2. 生成验证码
#     # hash值  验证码值  图片内容
#     name, text, image = captcha.generate_captcha()
#     # print("注册时的验证码为：", name, text, image)  # hash值  验证码值  图片内容
#     # 3. 将生成的图片验证码值作为value，存储到session中
#     session["captcha"] = text  # 通过session的方式将刚刚生成的图片验证码的值，进行存储，以便在登录的时候进行验证 图片验证码是否输入正确
#     # 返回响应内容
#     resp = make_response(image)
#     # 设置内容类型
#     resp.headers['Content-Type'] = 'image/jpg'
#
#     # print("captcha-------", session)
#     return resp

@passport_blue.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template('index/login.html')
    elif request.method == "POST":
        mobile = request.form.get('mobile')
        password = request.form.get("password")
        verify = request.form.get("verify")
        # print(mobile, password, verify)
        if not all([mobile, password, verify]):
            ret = {
                "status": 1001,
                "errmsg": "请填写所有数据！"
            }
            return jsonify(ret)

        if verify != "success":
            ret = {
                "status": 1002,
                "errmsg": "验证失败"
            }
            return jsonify(ret)

        user = db.session.query(User).filter(User.mobile == mobile, User.password_hash == password).first()
        if user:
            session['nick_name'] = user.nick_name
            session["user_id"] = user.id
            print('-'*40)
            # print(vip_get_webservertime(), user.vip_create_time)
            # print(type(vip_get_webservertime()), type(user.vip_create_time))
            if vip_get_webservertime() > user.vip_create_time:
                # print('进来了')
                user.vip_create_time = vip_default_time()
                user.vip = 0
                db.session.commit()
            ret = {
                "status": 0,
                "errmsg": "登录中..."
            }
            return jsonify(ret)
        else:
            ret = {
                "status": 1003,
                "errmsg": "用户名或密码错误"
            }
            return jsonify(ret)


@passport_blue.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "GET":
        return render_template("index/register.html")
    if request.method == "POST":
            # 获取提交的数据
            mobile = request.form.get("mobile")
            user_name = request.form.get("user_name")
            password = request.form.get("password")
            password1 = request.form.get("password1")
            verify = request.form.get("verify")
            mobile_verify = request.form.get("mobile_verify")

            # 判断是否有数据
            if not all([mobile, user_name, password, password1, verify, mobile_verify]):
                ret = {
                    "errno": 1001,
                    "errmsg": "请填写所有数据！"
                }
                return jsonify(ret)

            # 如果有数据,判断密码是否一致
            if password != password1:
                ret = {
                    "errno": 4,
                    "errmsg": "密码不一致！"
                }
                return jsonify(ret)

            # 判断验证码
            if verify != "success":
                ret = {
                    "errno": 1002,
                    "errmsg": "验证失败"
                }
                return jsonify(ret)

            # 查询
            info = db.session.query(User).filter(User.mobile == mobile).first()
            if info:
                # 有返回
                ret = {
                    "errno": 3,
                    "errmsg": "该手机已经注册过！"
                }
                return jsonify(ret)
            info = db.session.query(User).filter(User.nick_name == user_name).first()
            if info:
                # 有返回
                ret = {
                    "errno": 13,
                    "errmsg": "用户名已存在！"
                }
                return jsonify(ret)
            if mobile_verify != session.get("sms_code"):
                ret = {
                    "errno": 1011,
                    "errmsg": "验证码错误！"
                }
                return jsonify(ret)

            try:
                # 确认
                user = User()
                user.mobile = mobile
                user.nick_name = user_name
                user.password_hash = password
                user.vip_create_time = vip_default_time()
                db.session.add(user)
                db.session.commit()
                ret = {
                    "errno": 0,
                    "errmsg": "注册成功！"
                }
            except Exception as e:
                ret = {
                    "errno": 1012,
                    "errmsg": "注册失败！"
                }
            return jsonify(ret)


@passport_blue.route("/logout", methods=["GET", "POST"])
def logout():
    session.clear()
    ret = {
        "errno": 0,
        "errmsg": "退出成功"
    }

    return jsonify(ret)
    # return redirect(url_for('index_blue.index'))


@passport_blue.route("/verify", methods=["GET", "POST"])
def verify():
    if request.method == "GET":
        return render_template("index/verify.html")
    if request.method == "POST":
        # 获取数据
        mobile = request.form.get("mobile")
        verify_code = request.form.get("verify")

        if not all([mobile, verify_code]):
            ret = {
                "errno": 1004,
                "errmsg": "缺少参数"
            }
            return jsonify(ret)

        # 判断手机号是否注册
        user = db.session.query(User).filter(User.mobile == mobile).first()
        if not user:
            ret = {
                "errno": 2005,
                "errmsg": "此手机号未注册，请注册！"
            }
            return jsonify(ret)

        # 判断验证码是否正确
        if verify_code != session.get("sms_code"):
            ret = {
                "errno": 1005,
                "errmsg": "验证错误"
            }
            return jsonify(ret)

        try:
            # 查找数据
            session["mobile"] = mobile
            ret = {
                "errno": 0,
                "errmsg": "验证成功，请重置密码！"
            }
        except Exception as e:
            print("验证有误！")
            ret = {
                "errno": 1006,
                "errmsg": "验证有误！"
            }
        return jsonify(ret)


@passport_blue.route("/reset_pwd", methods=["GET", "POST"])
def reset_pwd():
    if request.method == "GET":
        return render_template("index/reset_pwd.html")
    if request.method == "POST":
        if request.method == "GET":
            return render_template("index/reset_pwd.html")
        elif request.method == "POST":
            # 获取数据
            password = request.form.get("password")
            password1 = request.form.get("password1")
            verify = request.form.get("verify")
            print(request.form)
            if not all([password, password1, verify]):
                ret = {
                    "status": 1007,
                    "errmsg": "请填写所有数据！"
                }
                return jsonify(ret)

            if password != password1:
                ret = {
                    "status": 1009,
                    "errmsg": "密码不一致！"
                }
                return jsonify(ret)

            if verify != "success":
                ret = {
                    "status": 1008,
                    "errmsg": "验证失败"
                }
                return jsonify(ret)
            try:
                mobile = session.get("mobile")
                user = db.session.query(User).filter(User.mobile == mobile).first()
                user.password_hash = password
                db.session.commit()
                ret = {
                    "errno": 0,
                    "errmsg": "重置成功！"
                }
            except Exception as e:
                ret = {
                    "errno": 1010,
                    "errmsg": "重置失败！"
                }
            return jsonify(ret)


@passport_blue.route('/smscode', methods=['POST'])
def send_sms_code():
    """
    发送短信验证码:
    1. 接收参数(`手机号mobile`, 并进行参数校验
    2. 对比图片验证码文本，如果一致
    3. 使用云通讯给`手机号mobile`发送短信验证码
    4. 返回应答，发送短信成功
    """
    # 取浏览器传递的json数据
    mobile = request.json.get('mobile')

    if not all([mobile]):
        ret = {
            "errno": 2003,
            "errmsg": "缺少参数"
        }
        return jsonify(ret)

    if not re.match(r'^1[3-9]\d{9}$', mobile):
        ret = {
            "errno": 2004,
            "errmsg": "手机号码格式不正确"
        }
        return jsonify(ret)

    # 4. 使用云通讯给`手机号mobile`发送短信验证码
    # 4.1 随机生成一个6位数字
    sms_code = str(random.randint(100000, 999999))

    # 调用阿里云接口，发送短信
    send_sms(mobile, sms_code)

    # 将发送的短信验证码 存储到session中
    session["sms_code"] = sms_code
    print("sms_code", sms_code)

    ret = {
        "errno": 0,
        "errmsg": "发送短信成功"
    }
    return jsonify(ret)